//
//  DDMusicPlayer.m
//  ialone
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 JasperSong. All rights reserved.
//

#import "DDMusicPlayer.h"

@interface DDMusicPlayer ()

@property (nonatomic, strong) AVPlayer *player;

@end


@implementation DDMusicPlayer

// 单例对象
+ (instancetype)shareMusicPlayerWithURLString:(NSString *)urlString{
    static DDMusicPlayer *musicPlayer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        musicPlayer = [[DDMusicPlayer alloc]init];
        musicPlayer.player = [[AVPlayer alloc]init];
         AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:urlString]];
        [musicPlayer.player replaceCurrentItemWithPlayerItem:item];
    });
    return musicPlayer;
}

- (void)play{
    [self.player play];
}
-(void)pause{
    [self.player pause];
}
- (void)stop{
    [self seekToTime:0];
    [self pause];
}

// 时间的跳转
-(void)seekToTime:(NSInteger)newTime{
    CMTime currentTime = self.player.currentTime;
    currentTime.value = newTime * currentTime.timescale;
    [self.player seekToTime:currentTime];
}

-(NSInteger)currentTime{
    if (self.player.currentTime.timescale == 0) {
        return 0;
    }
    return self.player.currentTime.value / self.player.currentTime.timescale;
}
-(NSInteger)finishTime{
    CMTime time = self.player.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value / time.timescale;
}
-(BOOL)isPlaying{
    if (self.player.rate == 1.0) {
        return YES;
    }else{
        return NO;
    }
    
}
// 快进10s
- (void)forward{
    if (self.finishTime - self.currentTime <= 10){
        [self seekToTime:self.finishTime];
    }else{
        [self seekToTime:(self.currentTime + 10)];
    }
}
// 快退10s
- (void)toBack{
    if (self.currentTime <= 10){
        [self seekToTime:0];
    }else{
        [self seekToTime:(self.currentTime - 10)];
    }
}


@end
